

import { Node, _decorator, BlockInputEvents, Vec2, sp, Vec3, UITransform, NodePool, Prefab, instantiate, resources } from "cc";
import { KeyBoardEvent } from "../KeyboardDefine";
import { KeyEventListener } from "../../core/GameInputListeners";
import { NodeKeyBoardProcessor } from "../../cocos/component/NodeKeyBoardProcessor";
import { InputKeyCode } from "../../core/InputConfig";
import GameInputEvent from "../../core/GameInputEvent";
import GEvent from "../../../cfw/event/GEvent";




const { ccclass, executionOrder } = _decorator;

/**
 * @packageDocumentation
 * @module event
 */

const BlockEvents = [Node.EventType.TOUCH_START, Node.EventType.TOUCH_END, Node.EventType.TOUCH_MOVE,
Node.EventType.MOUSE_DOWN, Node.EventType.MOUSE_MOVE, Node.EventType.MOUSE_UP,
Node.EventType.MOUSE_ENTER, Node.EventType.MOUSE_LEAVE, Node.EventType.MOUSE_WHEEL];

const _tempVec3 = new Vec3();

/**
 * @en  
 * This component will block all input events (mouse and touch) within the size of the node,
 * preventing the input from penetrating into the underlying node, typically for the background of the top UI.<br>
 * This component does not have any API interface and can be added directly to the scene to take effect.
 * @zh
 * 该组件将拦截所属节点尺寸内的所有输入事件（鼠标和触摸），防止输入穿透到下层节点，一般用于上层 UI 的背景。<br>
 * 该组件没有任何 API 接口，直接添加到场景即可生效。
 */
@ccclass('SuperBlockInput')
@executionOrder(-90)
export default class SuperBlockInput extends BlockInputEvents implements KeyEventListener {


    get isValid(): boolean {
        return this.node && this.node.isValid
    }


    private get keyProcessor(): NodeKeyBoardProcessor {
        let comp = this.node.getComponent(NodeKeyBoardProcessor)
        if (!comp) {
            comp = this.node.addComponent(NodeKeyBoardProcessor)
        }
        return comp;
    }
    onEnable() {
        //重置一下这个节点的事件处理器记录的配对事件
        this.node.eventProcessor.claimedTouchIdList.length = 0;
        for (let i = 0; i < BlockEvents.length; i++) {
            // supply the 'this' parameter so that the callback could be added and removed correctly,
            // even if the same component is added more than once to a Node.
            this.node.on(BlockEvents[i], this.stopPropagation, this);
        }
        //这里不能添加，隐藏后再显示后重新添加会遮挡子节点的事件
        this.keyProcessor.addKeyEventListener(this)
    }

    onDisable() {
        for (let i = 0; i < BlockEvents.length; i++) {
            this.node.off(BlockEvents[i], this.stopPropagation, this);
        }
        this.keyProcessor.removeKeyEventListener(this)
    }

    stopPropagation(event: any) {
        console.log('stopPropagation==== ')
        if (event.type == "touch-start") {
            // this.showClickEffect(event.getUILocation());
            console.log("SuperBlockInput " + this.node.name);
        }
        event.propagationStopped = true;
    }

    //屏幕点击特效
    public showClickEffect(location: Vec2): void {
        let node = this.getClickEffectFromPool();
        if (!node) {
            return;
        }
        // UIManager.getInstance().popupNode.addChild(node);
        let spine = node.getComponent(sp.Skeleton);

        //@ts-ignore
        let allAnim = Object.keys(spine.skeletonData.skeletonJson.animations);
        _tempVec3.set(location.x, location.y, 0);

        // node.setPosition(_tempVec3);
        node.worldPosition = _tempVec3;
        let clickEffect = spine.setAnimation(0, allAnim[Math.floor(Math.random() * (allAnim.length - 1)) + 1], false);
        spine.setTrackCompleteListener(clickEffect, () => {
            this.setClickEffectToPool(node);
            // item.destroy();
            // node.destroy();
        });
        this.playSound();
    }

    public clickEffectPool: NodePool;
    public getClickEffectFromPool(): Node {
        if (!this.clickEffectPool) {
            this.clickEffectPool = new NodePool();
        }
        let node: Node = this.clickEffectPool.get();
        if (!node) {
            let prefab: Prefab = resources.get("common/ClickEffect", Prefab);
            if (!prefab) {
                return null;
            }
            node = instantiate(prefab);
        }
        return node;
    }
    public setClickEffectToPool(node: Node): void {
        this.clickEffectPool?.put(node);
    }

    public get isActive() {
        return this.node.activeInHierarchy;
    }

    /**
     * 是否阻挡事件穿透
     */
    isBlockInput(): boolean {
        return this.isActive;
    }
    /**
     * 纯键盘按键按下回调
     * @param keyCode 按键键值
    */
    onKeyBoardPress(keyCode: InputKeyCode, event?: GameInputEvent): void {

    }
    /**
     * 纯键盘按键抬起回调
     * @param keyCode 按键键值
    */
    onKeyBoardRelease(keyCode: InputKeyCode, event?: GameInputEvent): void {
    }

    playSound() {
        GEvent.instance().emit(KeyBoardEvent.PLAY_AUDIO, 10138);
    }
}